package com.ran.sys.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ran.common.vo.JwtHelper;

import com.ran.sys.entity.Face;
import com.ran.sys.entity.User;
import com.ran.sys.mapper.FaceMapper;
import com.ran.sys.mapper.UserMapper;
import com.ran.sys.service.IFaceService;
import com.ran.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Service
public class FaceServiceImpl extends ServiceImpl<FaceMapper, Face> implements IFaceService {
    @Autowired
    private  RestTemplate restTemplate;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private FaceMapper faceMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User faceToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return null;
        }
        String userId = JwtHelper.getUserId(token);
        if (userId == null){
            return null;
        }
        String username = JwtHelper.getUsername(token);
        User User = userService.getUserInfoByUserId(userId);
        if (!User.getUsername().equals(username)) {
            return null;
        }
        User user = new User();
        int i = Integer.parseInt(userId);
        user.setId(i);
        user.setUsername(username);
        return user;
    }

    @Override
    public File dealFile(MultipartFile file) {

        if (file == null) {
               throw null;
        }
        String filePath = "/photo";//更改路径
        File pathFile = new File(filePath);
        if (pathFile.exists()) {
            pathFile.mkdirs();
        }
        String originalFileName = file.getOriginalFilename();
        String newfileName = UUID.randomUUID() + originalFileName;
        //封装上传文件位置的全路径
        File targetFile = new File(filePath, newfileName);
        //把本地文件上传到封装上传文件位置的全路径
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return targetFile;
    }

    //生成模板
    @Override
    public String sendRequest(File targetFile, User user) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("filename", user.getUsername());
        map.add("img_path",targetFile.getAbsolutePath());
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);

        String url1 = "http://localhost:5000/face";


            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url1, param, String.class);

            String body = responseEntity.getBody();
            //JSON格式转为List类型
            JSONObject jsonObject = JSONObject.parseObject(body);

             String templateStr = jsonObject.getString("obj");
//// 数组

        return templateStr;
    }



    @Override
    public String sendRequest3(File targetFile) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("filename", "a");
            map.add("img_path",targetFile.getAbsolutePath());
            HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);

            String url1 = "http://localhost:5000/face";


            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url1, param, String.class);

            String body = responseEntity.getBody();
            //JSON格式转为List类型
            JSONObject jsonObject = JSONObject.parseObject(body);

            String templateStr = jsonObject.getString("obj");
//// 数组

            return templateStr;
        }
// 数组





    @Override
    public User judgingUser(String vector) {
//        int id=-1;
        double temp=0.6;
        double obj =0.6;
        User user1=null;
        List<User> users=userMapper.selectList(null);
        for (User user:users){
            String template2=this.getTemplate(user);
            if (template2==null){
                continue;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.add("template1", vector);
            map.add("template2",template2);
            HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);

            String url2 = "http://localhost:5000/face3";

            try {
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url2, param, String.class);

                String body = responseEntity.getBody();
                //JSON格式转为List类型
                JSONObject jsonObject = JSONObject.parseObject(body);

                obj =Double.parseDouble(jsonObject.getString("obj"));
// 数组
            } catch (RestClientException e) {
                e.printStackTrace();

            }
            if (obj<temp){
                temp=obj;
                user1=user;}
            }

        return user1;


    }

    @Override
    public Map<String, Object> sendRequest4(File targetFile) {
        return null;
    }

    @Override
    public boolean insertFace(File file,User user, String template) {
        user.setPhotoAddress(file.getAbsolutePath());
        user.setFace(user.getId());
        boolean isSuccess = userService.updateById(user);
        if (!isSuccess) {
            return false;
        }
        Face face = new Face();

        face.setId(user.getId());
        face.setFaceList(template);

        Boolean success = save(face);
        return success;
    }

    //对比人脸
    @Override
    public Map<String, Object> sendRequest2(File targetFile, User user, String faceTemplate) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("filename", user.getUsername());
        map.add("img_path",targetFile.getAbsolutePath());
        map.add("template",faceTemplate);
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);

        String url2 = "http://localhost:5000/face2";

        String obj = null;
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url2, param, String.class);

            String body = responseEntity.getBody();
            //JSON格式转为List类型
            JSONObject jsonObject = JSONObject.parseObject(body);

            obj = jsonObject.getString("obj");
// 数组
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("value",obj);

        return result;
    }

    @Override
    public String getTemplate(User user) {
        User infoUser = userService.getUserInfoByUserId(String.valueOf(user.getId()));
        Face face = faceMapper.selectById(infoUser.getFace());
        if (face==null){
            return null;
        }
        String faceList = face.getFaceList();
        return faceList;
    }




}
